import os
from dnslib import RR, QTYPE, RCODE, TXT,DNSRecord,DNSHeader,DNSQuestion,CNAME
from dnslib.server import DNSServer, DNSHandler, BaseResolver, DNSLogger
import socket
import threading

class ZoneResolver(BaseResolver):
    def resolve(self, request, handler):
        x = request.questions[0]
        qq = str(x._qname)
        try:
            ip = socket.gethostbyname(qq)
        except:
            reply = request.reply()
            reply.header.rcode = getattr(RCODE,'NXDOMAIN')
            print ('error %s'%qq)
            return reply     
        reply = request.reply()

        reply.add_answer(*RR.fromZone("%s 60 A %s"%(qq,ip)))
        return reply   

def main():
    udp_server = DNSServer(ZoneResolver(), port=59832,tcp=True, address='')
    udp_server.start()


if __name__ == '__main__':
    #pip3 install dnslib -i https://pypi.tuna.tsinghua.edu.cn/simple
    #os.system('iptables -t nat -A OUTPUT -p tcp -d 8.8.8.8 --dport 53 -j REDIRECT --to-port 59832')
    main()
    
